from rest_framework.metadata import BaseMetadata
from .models import Strategy
import traceback
from ztp_backend import settings


def build_choices(choices):
    choices = map(lambda x: x if isinstance(x, (list, tuple)) else (x, x), choices)
    return {'choices': [{'value': x[0], 'display_name': x[1]} for x in choices]}


class StrategyMetadata(BaseMetadata):
    """策略视图类的元数据，用于OPTIONS方法"""
    def determine_metadata(self, request, view):
        category = request.GET.get('category', '')
        # print("category : ", category)
        STRATEGY_CHANNELS_ = ()  # Android,Windows,Web,Linux
        if category:
            if category in ("身份认证",):
                STRATEGY_CHANNELS_ = (
                    (1, 'Android'),
                    (2, 'Windows'),
                    (3, 'Web'),
                    (4, 'Linux'),
                )
            elif category in ("外设管控", "实时防护",):
                STRATEGY_CHANNELS_ = (
                    (2, 'Windows'),
                )
            elif category in ("安全基线",):
                STRATEGY_CHANNELS_ = (
                    (2, 'Windows'),
                    (4, 'Linux'),
                )
            elif category in ("设备登录", "终端威胁",):  # 终端安全 改为 终端威胁
                STRATEGY_CHANNELS_ = (
                    (1, 'Android'),
                    (2, 'Windows'),
                    (4, 'Linux'),
                )
            elif category in ("主机审计", "基础配置",):  # 终端安全 改为 终端威胁
                STRATEGY_CHANNELS_ = (
                    (1, 'Android'),
                    (2, 'Windows'),
                    )
            else:
                pass
        else:
            STRATEGY_CHANNELS_ = (
                (1, 'Android'),
                (2, 'Windows'),
                (3, 'Web'),
                (4, 'Linux'),
            )

        return {
            'name': view.get_view_name(),
            'description': view.get_view_description(),
            'renders': [renderer.media_type for renderer in view.renderer_classes],
            'parses': [parser.media_type for parser in view.parser_classes],
            'actions': {
                'POST': {
                    'category': build_choices(self.get_categories()),
                    'level': build_choices(Strategy.STRATEGY_LEVELS),
                    'channel': build_choices(STRATEGY_CHANNELS_),
                },
            }
        }

    @classmethod
    def get_categories(cls):
        try:
            if not hasattr(cls, 'category_list'):
                category_list = list(Strategy.objects.distinct('category').values_list('category', flat=True))
                skip_values = set()
                if settings.NO_STG_DL:
                    skip_values.add('文件下载')
                if settings.NO_STG_SHR:
                    skip_values.add('文件共享')
                if settings.NO_STG_MAIL:
                    skip_values.add('邮件安全')
                if settings.NO_STG_TERM:
                    skip_values.add('终端威胁')
                for name in skip_values:
                    if name in category_list:
                        category_list.remove(name)
                cls.category_list = category_list
            return cls.category_list
        except Exception:
            traceback.print_exc()
